import re
import requests
from  request_handle import *





class Douban_getter:
    def __init__(self,name):
        self.name = name
        self.pageurl = self.get_search_path('https://www.douban.com/search?cat=1002&q=', name)


    def reini(self,name):
        self.name = name
        self.pageurl = self.get_search_path('https://www.douban.com/search?cat=1002&q=', name)
        self.type_attr = {}



    def get_search_path(self,url, name):
        content = requests.get(url + name).content.decode('utf-8')
        if '<p class="no-result">' in content:
            return None
        content = get_subcontent(content, '<h3>', '</h3>')
        content = get_subcontent(content, 'href', 'target=')
        spl = content.split('"')
        content = [s for s in spl if "http" in s]
        content = content[0]
        return content

    def get_tags(self, content):
        content = get_subcontent(content,'<div class="tags-body">','<div id="dale_movie_subject_inner_middle">')
        content = content.replace("</a>","||")
        content = remove_html(content).replace(" ","")
        content = content.split("||")
        return [c.strip() for c in content if len(c) > 0]

    def get_type(self, content):
        content = get_subcontent(content,'<div id="info">','<div id="interest_sectl">')
        content = content.split('<span class="pl">')
        ctype = [c for c in content if "类型" in c]
        if len(ctype) > 0:
            ctype = ctype[0]
        else:
            return None
        ctype = get_rightpart(ctype,"类型:",True)
        ctype = remove_html(ctype).replace(" ","").strip()
        return ctype.split("/")

    def get_rate(self, content):
        content = get_subcontent(content,'<div class="rating_self clearfix" typeof="v:Rating">','<div id="interest_sect_level" class="clearfix">')
        if "暂无评分" in content:
            return None
        rate = get_subcontent(content,'<strong class="ll rating_num" property="v:average">','<span property="v:best" content="10.0">')
        rate = remove_html(rate)
        ratesum = get_subcontent(content,'<div class="rating_sum">','<span class="stars5 starstop" title="力荐">')
        ratesum = remove_html(ratesum)
        ratesum = re.sub("\s*",'',ratesum)
        if 'rating_betterthan' in content:
            subrate = get_subcontent(content,'<div class="ratings-on-weight">','<div class="rating_betterthan">')

        else:
            subrate = get_subcontent(content,'<span class="stars5 starstop" title="力荐">',' <div id="interest_sect_level" class="clearfix">')
        subrate = remove_html(subrate).strip()
        subrate = re.sub("\s*","",subrate)
        subrate = subrate.replace(" ","").replace("%",'% ')
        subrate = re.sub('[1-5]星','',subrate)

        subrate = subrate.split(" ")
        subrate = [s.strip() for s in subrate if len(s) > 0]
        return [rate,ratesum,subrate]

    def get_realname(self,content):
        content = get_subcontent(content,'<span property="v:itemreviewed">','</h1>')
        content = remove_html(content)
        content = re.sub("\s*","",content)
        return content
    def get_realtype(self,content):
        content = get_subcontent(content,'<div class="nav-logo">','<div class="nav-search">')
        return remove_html(content).strip().replace("豆瓣",'')
    
    def get_info(self,type_attr = {'type','rate','tags'}):
        if hasattr(self, 'pageurl'):
            if self.pageurl is None:
                return {'name':self.name,'错误':'搜索不到相关的信息'}

        if hasattr(self,'type_attr'):
            if self.type_attr == type_attr:
                return self.info_list
            else:
                print("reload")
        else:
            print("noattr")

        self.content = requests.get(self.pageurl).content.decode('utf-8')
        content = self.content

        info_list = dict()
        info_list['search_name'] = self.name
        info_list['real_name'] = self.get_realname(content)
        info_list['real_type'] = self.get_realtype(content)
        if "type" in type_attr:
            temp =  self.get_type(content)
            if temp is None:
                info_list['type'] = "[无分类]"
            else:
                info_list['type'] = temp
        if "rate" in type_attr:
            temp = self.get_rate(content)
            if temp is None:
                info_list["rate"] = "[无评分]"
            else:
                info_list["rate"] = temp
        if "tags" in type_attr:
            info_list['tags'] = self.get_tags(content)
        self.type_attr = type_attr
        self.info_list = info_list
        return info_list

    def get_with_format(self,iformat = 'txt'):
        if 'txt' in iformat:
            strs = ""
            for k in self.info_list:
                strs = strs + "{}:{}\n".format(k,str(self.info_list[k]))
            strs = strs + '========\n'
            return strs

if __name__ =='__main__':
    getter = Douban_getter('汪汪队立大功')
    getter.get_info()
    print(getter.get_with_format())
    
    
